﻿using AutoMapper;
using MediatR;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.App.Applications.Slaughter
{
    public class SlaughterEaditCommandHandler : IRequestHandler<SlaughterEaditCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_Slaughter> slaughterRepository;
        private readonly IBaseRepository<T_Traceability> tranceRepository;
        private readonly IMapper mapper;

        public SlaughterEaditCommandHandler(IBaseRepository<T_Slaughter> slaughterRepository, IMapper mapper, IBaseRepository<T_Traceability> tranceRepository)
        {
            this.slaughterRepository = slaughterRepository;
            this.mapper = mapper;
            this.tranceRepository = tranceRepository;
        }

        public async Task<APIResult<int>> Handle(SlaughterEaditCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnum.ok;
            var slaughter = slaughterRepository.GetAll().FirstOrDefault(x => x.Batch == request.Batch);
            if (slaughter == null)
            {
                result.Message = "保存成功";
                request.ID = 0;
                var model = mapper.Map<T_Slaughter>(request);
                result.Data = await slaughterRepository.Add(model);
                var data = tranceRepository.GetAll().FirstOrDefault(x => x.Batch == request.Batch);
                data.Perfection += 30;
                await tranceRepository.Update(data);
                return await Task.FromResult(result);
            }
            else 
            {
                result.Message = "修改成功";
                var model = mapper.Map(request, slaughter);
                result.Data = await slaughterRepository.Update(model);
                return await Task.FromResult(result);
            }
        }
    }
}
